const Koa = require('koa')
const static = require('koa-static');
const body = require('koa-body');
const Router = require('koa-router');
const fs = require('fs');
const path = require('path');

const app = new Koa();

app.use(body({
    multipart: true
}));

app.use(static(__dirname + '/public'));

const router = Router();

router.get('/', (ctx) => {
    ctx.render('./index.html')
})


const saveFile = (file) => {
    let filename = Math.random().toString(32) + file.name

    let targetPath = path.join(__dirname, '/upload', filename)
    let filePath = file.path

    let r = fs.createReadStream(filePath)
    let w = fs.createWriteStream(targetPath)

    r.pipe(w);
}    

router.post('/upload', ctx => {
    console.log(
        ctx.request.files
    )
    let file_list = ctx.request.files.file_list
    if (Array.isArray(file_list)) {
        for (let file of file_list) {
            saveFile(file)
        }
    } else {
        saveFile(file_list)
    }
    ctx.body = {
        success: true,
        msg: ''
    }
})

app.use(router.routes())

app.listen(3002, () => {
    console.log('server is runing');
})
